package gdonly.top.signin.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.RequestBody;

import org.json.JSONException;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import gdonly.top.signin.business.Application;
import gdonly.top.signin.entity.User;

/**
 * Created by zhuzhuxia on 2017/4/28.
 */
public class DatabaseQuery {

    public static String hostIp = "http://192.168.1.102:8080/SignInServer/";
    //public static String hostIp = "http://www.gdonly.top:8080/SignInServer/";
    public static final int TIMER_HAS_DOWN = -2;

    private static final int INTERVAL = 4000;
    private static final int COUNT_DOWN = 5 * 60 * 1000;

    public static User login(final String userId, final String pwd){
        //已经实现好，再实现完成数据库的功能之后去掉注释。
        Callable<User> loginCall = new Callable<User>(){
            @Override
            public User call() throws Exception {
                Log.e("TAG","login:ThreadId:"+Thread.currentThread().getId());

                RequestBody body = new FormEncodingBuilder()
                        .add("user_id", userId)
                        .add("pwd", pwd)
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "LoginSevelet");
                    Log.e("TAG",result);
                    return JsonUtil.getUserFromJson(result);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }

            }
        };
        FutureTask<User> futureTask = new FutureTask<User>(loginCall);

        new Thread(futureTask).start();


        try {
            while(!futureTask.isDone()){
                Thread.sleep(100);
            }


            return futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 班级总人数
     * @param classId
     * @return
     */
    public static int queryHeadCount(final Activity activity, final String classId){

        Callable<Integer> getHeadCountCall = new Callable<Integer>(){
            @Override
            public Integer call() throws Exception {
                Log.e("TAG","queryHead:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", classId)
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "GetHeadCount");
                    Log.e("TAG", result);
                    return JsonUtil.getHeadCountFromJson(result);
                } catch (IOException e) {
                    e.printStackTrace();
                    return queryHeadCount(activity, classId);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return queryHeadCount(activity, classId);
                }

            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(getHeadCountCall);

        try {

            if(result.get() == null){
                return queryHeadCount(activity, classId);
            }
            return (int)result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return queryHeadCount(activity, classId);
        } catch (ExecutionException e) {
            e.printStackTrace();
            return queryHeadCount(activity, classId);
        }
    }

    /**
     * 实际签到人数
     * @param classId
     * @return
     *
     *
     */

    private static boolean cancelQueryActual = false;

    public static void cancelQueryActual(){
        if(timer != null){
            timer.cancel();
        }
        if(task != null){
            task.cancel();
        }
    }
    private static Timer timer;
    private static TimerTask task;

    public static void queryActualSigned(Activity activity, final String classId, final Handler handler) {

        cancelQueryActual = false;

         task = new TimerTask() {

            final RequestBody body = new FormEncodingBuilder()
                    .add("class_id", classId)
                    .build();

            @Override
            public void run() {

                Log.e("TAG","queryActual:ThreadId:"+Thread.currentThread().getId());

                Log.e("TAG", "run......");

                Log.e("TAG", "Tick.....");

                try {

                    String result = HttpUtil.post(body, hostIp + "GetActualSigned");
                    Log.e("TAG", "getActual:" + result);
                    int actual = JsonUtil.getActualSigned(result);
                    Message message = new Message();
                    message.what = actual;
                    handler.sendMessage(message);

                } catch (IOException e) {
                    e.printStackTrace();

                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }
        };
        timer = new Timer();
        timer.schedule(task, INTERVAL, INTERVAL);

//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                Log.e("TAG","run......");
//                final RequestBody body = new FormEncodingBuilder()
//                        .add("class_id", classId)
//                        .build();
//
//                CountDownTimer timer = new CountDownTimer(COUNT_DOWN, INTERVAL) {
//                    @Override
//                    public void onTick(long millisUntilFinished) {
//
//                        Log.e("TAG","Tick.....");
//
//                        try {
//
//                            String result = HttpUtil.post(body, hostIp + "GetActualSigned");
//                            Log.e("TAG", "getActual:" + result);
//                            int actual = JsonUtil.getActualSigned(result);
//                            Message message = new Message();
//                            message.what = actual;
//                            handler.sendMessage(message);
//
//                        } catch (IOException e) {
//                            e.printStackTrace();
//
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//
//                        }
//                    }
//
//                    @Override
//                    public void onFinish() {
//
//                        Message message = new Message();
//                        message.what = TIMER_HAS_DOWN;
//                        handler.sendMessage(message);
//                    }
//                };
//                timer.start();
//            }
//        };
//        ((Application)activity.getApplication()).addThread(runnable);
    }

    /**
     * 启动签到开关
     */
    public static void signEnabled(Activity activity , final User user){

        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                Log.e("TAG","signEnabled:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", user.getClassId())
                        .build();
                try {
                    HttpUtil.post(body, hostIp + "SignEnabled");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        ((Application)activity.getApplication()).addThread(runnable);

    }

    /**
     * 关闭签到开关
     */
    public static void signDisenabled(Activity activity , final User user){


        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.e("TAG","signDisEnabled:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id",user.getClassId())
                        .build();
                try {
                    HttpUtil.post(body, hostIp + "SignDisEnabled");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        ((Application)activity.getApplication()).addThread(runnable);

    }

    /**
     * 学生签到
     */
    public static void sign(Activity activity , final User user) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.e("TAG","sign:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("id", user.getId())
                        .build();
                try {
                    HttpUtil.post(body, hostIp + "Sign");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        ((Application)activity.getApplication()).addThread(runnable);
    }

    /**
     * 查询签到开关是否已经开启
     * @return
     */
    public static boolean queryEnableSign(final Activity activity, final User user) {
        Callable<Boolean> isSignEnableCall = new Callable<Boolean>(){
            @Override
            public Boolean call() throws Exception {
                Log.e("TAG","queryEnableSign:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", user.getClassId())
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "GetSignEnable");
                    Log.e("TAG", result);
                    return JsonUtil.isSignEnable(result);
                }
                catch (IOException e) {
                    e.printStackTrace();
                    return queryEnableSign(activity, user);
                }
                catch (JSONException e) {
                    e.printStackTrace();
                    return queryEnableSign(activity, user);
                }

            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(isSignEnableCall);

//        FutureTask<Boolean> futureTask = new FutureTask<Boolean>(isSignEnableCall);

//        new Thread(futureTask).start();
        try {
//            while(!futureTask.isDone()){
//                Thread.sleep(100);
//            }

            if(result.get()!= null) {
                return (boolean)result.get();
            }
            return queryEnableSign(activity, user);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
            return queryEnableSign(activity, user);
        }
        catch (ExecutionException e) {
            e.printStackTrace();
            return queryEnableSign(activity, user);
        }


    }

    /**
     * 得到班长的信息，用来匹配周围的wifi是否含有班长的热点
     * @return
     */
    public static User getMonitorInfo(final Activity activity, final User user){

        Callable<User> getMonitor = new Callable<User>(){
            @Override
            public User call() throws Exception {
                Log.e("TAG","getMonitorInfo:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", user.getClassId())
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "GetMonitor");
                    Log.e("TAG",result);
                    return JsonUtil.getUserFromJson(result);
                } catch (IOException e) {
                    e.printStackTrace();
                    return getMonitorInfo(activity, user);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return getMonitorInfo(activity, user);
                }

            }
        };

        Future<Object> result = ((Application)activity.getApplication()).submitTask(getMonitor);

        try {

            return (User) result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return getMonitorInfo(activity, user);
        } catch (ExecutionException e) {
            e.printStackTrace();
            return getMonitorInfo(activity, user);
        }

    }

    /**
     * 主要用于班长上传自己的ssid
     */
    public static void uploadSelfInfo(Activity activity, final User user){

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.e("TAG","uploadSelInfo:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("ssid", user.getSsid())
                        .add("id", user.getId())
                        .build();
                try {
                    HttpUtil.post(body, hostIp + "UploadInfo");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        ((Application)activity.getApplication()).addThread(runnable);
    }

    public static List<User> querryTruntUsers(final Activity activity, final String classId, final String date, final String courseId){
        Callable<List<User>> queryCall = new Callable<List<User>>(){
            @Override
            public List<User> call() throws Exception {

                Log.e("TAG","queryTruntUsers:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()

                        .add("class_id", classId)
                        .add("date", date)
                        .add("course_id",courseId)
                        .build();

                try {
                    String result = HttpUtil.post(body, hostIp + "GetTrunt");
                    Log.e("TAG", result);
                    return JsonUtil.getUsersFromJson(result);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("TAG","exec1..........");
                    return querryTruntUsers(activity, classId, date, courseId);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("TAG", "exec2..........");
                    return querryTruntUsers(activity, classId, date, courseId);
                }
            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(queryCall);
        try {
            if(result.get() == null){
                Log.e("TAG","exec3..........");
                return querryTruntUsers(activity, classId, date, courseId);
            }
            return (List<User>) result.get();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
            Log.e("TAG", "exec4..........");
            return querryTruntUsers(activity, classId, date, courseId);
        } catch (ExecutionException e) {
            e.printStackTrace();
            Log.e("TAG", "exec5..........");
            return querryTruntUsers(activity, classId, date, courseId);
        }

    }
    /**
     *
     */

    public static String getRecordsByUserId(final String userId, final Activity activity){
        Callable<String> getHeadCountCall = new Callable<String>(){
            @Override
            public String call() throws Exception {
                Log.e("TAG","queryHead:ThreadId:"+Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("user_id", userId)
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "GetRecordsByUserId");
                    Log.e("TAG", result);
                    return result;
                } catch (IOException e) {
                    e.printStackTrace();
                    return getRecordsByUserId(userId, activity);
                }

            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(getHeadCountCall);
        try {
            return (String) result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return getRecordsByUserId(userId, activity);
        } catch (ExecutionException e) {
            e.printStackTrace();
            return getRecordsByUserId(userId, activity);
        }

    }

    public static String getCourseSignInfo(final String classId, final String courseId, final Activity activity){
        Callable<String> getHeadCountCall = new Callable<String>(){
            @Override
            public String call() throws Exception {
                Log.e("TAG", "getCourseSignInfo :ThreadId:" + Thread.currentThread().getId());
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", classId)
                        .add("course_id", courseId)
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "QueryCourseInfo");
                    Log.e("TAG", result);
                    return result;
                } catch (IOException e) {
                    e.printStackTrace();
                    return getCourseSignInfo(classId, courseId, activity);
                }

            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(getHeadCountCall);
        try {
            return (String) result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return getCourseSignInfo(classId, courseId, activity);
        } catch (ExecutionException e) {
            e.printStackTrace();
            return getCourseSignInfo(classId, courseId, activity);
        }
    }
    public static String getStusInCourseSign(final String classId, final String date, final String courseId, final Activity activity){
        Callable<String> getHeadCountCall = new Callable<String>(){
            @Override
            public String call() throws Exception {
//                Log.e("TAG", "getStusCourseSign :ThreadId:" + Thread.currentThread().getId());
                Log.e("TAG",classId + courseId +date );
                RequestBody body = new FormEncodingBuilder()
                        .add("class_id", classId)
                        .add("course_id", courseId)
                        .add("date",date)
                        .build();
                try {
                    String result = HttpUtil.post(body, hostIp + "GetStuFromCourse");
                    Log.e("TAG", result);
                    return result;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }
        };
        Future<Object> result = ((Application)activity.getApplication()).submitTask(getHeadCountCall);

        try {
            return (String) result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }
}
